package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"product/model/cache"
	"product/model/mysql"
	"product/productrpc/internal/svc"
	"product/productrpc/productrpc"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductListLogic {
	return &ProductListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 商品列表
func (l *ProductListLogic) ProductList(in *productrpc.ProductListRequest) (*productrpc.ProductListResponse, error) {
	// todo: add your logic here and delete this line
	page := in.Page
	if page <= 0 {
		page = 1
	}

	Size := in.Size
	switch {
	case Size > 100:
		Size = 100
	case Size <= 0:
		Size = 10
	}
	offset := (page - 1) * Size
	var product []mysql.Products
	mysql.DB.Debug().Offset(int(offset)).Limit(int(Size)).Where("title like ?", "%"+in.Title+"%").Order("price desc").Find(&product)

	key := fmt.Sprintf("ProductList%d%d", in.Page, in.Size)

	result, _ := cache.Rdb.Get(l.ctx, key).Result()

	if result == "" {
		marshal, _ := json.Marshal(&product)
		cache.Rdb.Set(l.ctx, key, marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(result), &product)
	}

	var productlists []*productrpc.ProductList
	for _, i2 := range product {
		list := productrpc.ProductList{
			Title:        i2.Title,
			UserId:       i2.UserId,
			Price:        float32(i2.Price),
			BrowseNumber: i2.BrowseNumber,
			Image:        i2.Image,
			ClassId:      i2.ClassId,
		}
		productlists = append(productlists, &list)
	}

	return &productrpc.ProductListResponse{
		List: productlists,
	}, nil
}
